package presenters;

import data.Account;
import data.AccountCorrectCredentials;
import data.AccountExists;
import data.AccountIsLocked;
import data.DBInterfaceError;
import data.Session;
import android.app.Activity;
import android.view.View;
import views.IFieldView;

/**
 * Handles logic and button presses from view
 * 
 * @author Kelsey
 */
public class LoginPresenter {

	/** View of Login */
	private final IFieldView myView;

	/** Activity in use */
	private final Activity activity;

	/**
	 * Creates a LoginPresentor
	 * 
	 * @param view
	 */
	public LoginPresenter(IFieldView view) {
		myView = view;
		activity = (Activity) myView;
	}

	/**
	 * hides the soft keyboard
	 */
	public void hideSoftKeyboard() {
		myView.hideSoftKeyboard(activity.getCurrentFocus());
	}

	/**
	 * WHen the on loginbutton is clicked, this method, does its sexy magic
	 * 
	 * @param userName
	 *            - the username
	 * @param password
	 *            - the password
	 * @param source
	 *            - the source
	 */
	public void onLoginAcceptClick(String userName, String password, View source) {
		final Account account = new Account();
		account.setAccountName(userName);
		account.setPassword(password);
		boolean success = false;
		boolean locked = false;
		try {
			if (new AccountExists(activity, account).getResult()) {
				try {
					success = new AccountCorrectCredentials(activity, account)
							.getResult();
					locked = new AccountIsLocked(activity, account).getResult();
				} catch (DBInterfaceError e) {
					e.printStackTrace();
				}
			}
		} catch (DBInterfaceError e) {
			e.printStackTrace();
		}
		if (locked) {
			myView.showToast("locked");
		} else if (success) {
			Session session = (Session) activity.getApplicationContext();
			session.setAccountName(userName);

			myView.showToast("success");
			myView.advance(source);
		} else {
			myView.showToast("failure");
		}
	}

	/**
	 * this gets called when the register button gets clicked
	 * 
	 * @param source
	 *            - the source
	 */
	public void onLoginRegisterClick(View source) {
		myView.advance(source);
	}

}